import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Router} from '@angular/router';

@Component({
  selector: 'app-book-type-list',
  templateUrl: './book-type-list.component.html',
  styleUrls: ['./book-type-list.component.css']
})
export class BookTypeListComponent implements OnInit {

  typeList: Array<any>;
  pager = {
    number: 0,
    size: 10,
    first: true,
    last: false,
    totalPages: 0,
    items: [],
  };

  pre() {
    if (!this.pager.first) {
      this.pager.number--;
      this.getList()
    }
  }

  next() {
    if (!this.pager.last) {
      this.pager.number++;
      this.getList()
    }
  }

  goTo(n) {
    this.pager.number = n;
    this.getList()
  }

  setPager(pager) {
    this.pager.number = pager.number;
    this.pager.size = pager.size;
    this.pager.first = pager.first;
    this.pager.last = pager.last;
    this.pager.totalPages = pager.totalPages;
    this.pager.items = Array.from({length: pager.totalPages}, (v, i) => i)
  }


  getList() {
    this.http.post('booktype/getBookTypeList', null, {
      params: {
        page: this.pager.number,
        size: this.pager.size
      }
    }).map(response => response.json())
      .subscribe(data => {
        if (data.code === 0) {
          this.typeList = data.data.content;
          this.setPager(data.data)
        } else {
          alert(data.msg)
        }
      })
  }

  del(id) {
    if (confirm('确定要删除吗?')) {
      this.http.post('booktype/delete', null, {
        params: {
          id: id
        }
      }).map(response => response.json())
        .subscribe(data => {
          if (data.code === 0) {
            this.getList()
          } else {
            alert(data.msg)
          }
        })
    }
  }

  add() {
    this.router.navigate(['book-type-edit', 'add'])
  }

  edit(id) {
    this.router.navigate(['book-type-edit', id])
  }

  constructor(private http: Http, private router: Router) {
  }

  ngOnInit() {
    this.getList()
  }

}
